﻿using System;
using System.Globalization;
using Jayden.Dll.Core.Persistence.Enums;
using Jayden.Dll.Entities.Common;
using Jayden.Dll.Web.Events;
using Jayden.Dll.Web.HtmlControls;
using Jayden.Dll.Web.Json;

namespace Jayden.Dll.Web.Controls
{
	public class ContactForm : Form
	{
		public delegate void OnContactSuccess(HttpHandlerContext context, Contact contact);

		public class ContactCommandHandler : HttpCommandHandler
		{
			public ContactCommandHandler() : this("Contact") { }
			public ContactCommandHandler(string command)
				: base(command)
			{
				RegisterEvent("ContactSuccess");
			}
			public event OnContactSuccess ContactSuccess { add { AddEvent<OnContactSuccess>("ContactSuccess", value); } remove { RemoveEvent<OnContactSuccess>("ContactSuccess", value); } }

			protected override void ProcessCommand(HttpHandlerContext context, string command)
			{
				string userTitle = context.Context.Request["userTitle"];
				string cultureCode = context.Context.Request["cultureCode"];
				string email = context.Context.Request["email"];
				string lastName = context.Context.Request["lastName"];
				string firstName = context.Context.Request["firstName"];
				string title = context.Context.Request["title"];
				string body = context.Context.Request["body"];
				string category = context.Context.Request["category"];


				ContactDataAccess contactDataAccess = context.UnitOfWork.DataAccessManager.GetDataAccess<ContactDataAccess, Contact>();
				if (contactDataAccess != null)
				{
					Contact contact = new Contact(context.UnitOfWork);
					contact.Body = body;
					contact.Title = title;
					contact.UserTitle = userTitle;
					contact.Email = email;
					contact.CultureCode = cultureCode;
					contact.LastName = lastName;
					contact.FirstName = firstName;
					contact.UserName = context.Context.User.Identity.Name;
					contact.CreationDate = DateTime.Now;
					contact.Category = category;
					contact.State = ObjectState.New;

					context.UnitOfWork.MarkNew(contact);
					context.UnitOfWork.Commit();

					Invoke("ContactSuccess", context, contact);
				}

			}
		}

		private Select m_UserTitle;
		private Input m_Category;
		private Input m_LastName;
		private Input m_FirstName;
		private Input m_Email;
		private Select m_CultureCode;
		private Input m_Title;
		private Textarea m_Body;

		private Button m_Send;

		public override void Load(System.Xml.XmlNode node, HtmlControlLoader loader)
		{
			base.Load(node, loader);
			if (Id == null)
				Id = "contactForm";

			m_UserTitle = GetFormElement<Select>("userTitle");
			m_CultureCode = GetFormElement<Select>("cultureCode");
			m_Email = GetFormElement<Input>("email");
			m_Category = GetFormElement<Input>("category");
			m_LastName = GetFormElement<Input>("lastName");
			m_FirstName = GetFormElement<Input>("firstName");
			m_Title = GetFormElement<Input>("title");
			m_Body = GetFormElement<Textarea>("body");
			m_Send = GetFormElement<Button>("send", "command");
		}

		public void LinkLabels()
		{
			FindLabel(m_UserTitle);
			FindLabel(m_CultureCode);
			FindLabel(m_Email);
			FindLabel(m_Category);
			FindLabel(m_LastName);
			FindLabel(m_FirstName);
			FindLabel(m_Title);
			FindLabel(m_Body);
		}

		private void FillFromConfiguration(HttpHandlerContext context)
		{
			string[] langs = context.Configuration.GetValues("Languages/Lang/@lang");
			foreach (string lang in langs)
			{
				CultureInfo cultureInfo = new CultureInfo(lang);
				m_CultureCode.AddOption(lang, cultureInfo.EnglishName);
			}
		}

		public override void ProcessHtmlRequest(HttpHandlerContext context)
		{
			base.ProcessHtmlRequest(context);
			LinkLabels();
			FillFromConfiguration(context);
			ContactCommandHandler handler = context.HandlerManager.GetHandler<ContactCommandHandler>();
			handler.ContactSuccess += new OnContactSuccess(ContactSuccess);
		}

		public override void ProcessJsonRequest(HttpHandlerContext context)
		{
			base.ProcessJsonRequest(context);
			LinkLabels();
			ContactCommandHandler handler = context.HandlerManager.GetHandler<ContactCommandHandler>();
			handler.ContactSuccess += new OnContactSuccess(ContactSuccess);
		}

		public override void ProcessJsRequest(HttpHandlerContext context)
		{
			base.ProcessJsRequest(context);
			string id = Id;
			context.Js[id].AppendAjaxSubmit(this, m_Send);
			context.Js[id].AppendAjaxHtmlHandler(this, false, false);
		}

		public bool ServerNoMail { get { return GetServerAttribute("no-mail", null) == "true"; } }
		public string ServerMailer { get { return GetServerAttribute("mailer"); } }

		private void ContactSuccess(HttpHandlerContext context, Contact user)
		{
			ChildControls.Clear();
			if (!ServerNoMail)
			{
				Mailer mailer = context.GetMailer(ServerMailer);
				if (mailer != null)
				{
					string[] to = GetServerAttribute("to", "jonv11@gmail.com").Split(';');
					string[] cc = GetServerAttribute("cc", string.Empty).Split(';');
					string[] bcc = GetServerAttribute("bcc", string.Empty).Split(';');
					mailer.Send(
						to,
						cc,
						bcc,
						context.Translator.Translate("New contact request from your website."),
						context.Translator.Translate("A new contact request has been sent via your website.")
					);
					AddText<P>(context.Translator.Translate("Your contact request has been sent successfully."));
				}
				else
					context.Logger.Warning("Mailer with id '{0}' cannot be found.", ServerMailer);
			}
			AddText<P>(context.Translator.Translate("Your contact request has been saved to database successfully."));

			if (context.Json != null)
			{
				JsonObject form = new JsonObject();
				form.Add("html", ToInnerHtml(context.Translator));
				context.Json.Add(Id, form);
			}
		}

	}
}
